<template>
  <view>
    <view class="status_bar"></view>
    <!-- #ifndef MP-WEIXIN -->
    <u-navbar title="搜索" :background="background"> </u-navbar>
    <!-- #endif -->
    <view class="search_good">
      <view class="flex search_key flex_col_center padding">
        <!-- #ifndef APP-PLUS -->
        <image
          v-if="from == 'goods'"
          src="../../static/image/voice.png"
          class="voice"
          @click="showPop()"
          mode=""
        >
        </image>
        <!-- #endif -->
        <view class="search flex flex_col_center">
          <text class="custom-icon custom-icon-chazhao"></text>
          <input
            type="text"
            :value="value"
            @input="inputAction"
            :placeholder="placeholder"
            placeholder-class="twelve_font gray_font"
            class="search_input"
          />
        </view>
        <text v-if="value" class="cancel" @click="searchGood()">搜索</text>
        <text v-else class="cancel" @click="back">取消</text>
      </view>

      <view class="recommend_good content" v-if="hiddenSearch">
        <view v-if="from == 'order'" class="all_good flex flex_row_between">
          <view
            class="order"
            v-for="item in dataList"
            :key="item.id"
            @click="toDetail(item.id)"
          >
            <my-orderlist :item="item" @clickbtn="btnAction"></my-orderlist>
          </view>
        </view>
        <view
          v-else-if="from == 'returnorder'"
          class="all_good flex flex_row_between"
        >
          <view
            class="order"
            v-for="item in dataList"
             :key="item.id"
            @click="toDetail(item.id)"
          >
            <my-returnorderlist
              :item="item"
              @clickbtn="btnAction"
            ></my-returnorderlist>
          </view>
        </view>
        <view v-else class="all_goods">
          <view class="sign_good" v-for="item in dataList" :key="item.id">
            <my-listrow
              :data="item"
              :showPrice="showPrice"
              @showCart="$refs.cart.open(item)"
            ></my-listrow>
          </view>
        </view>
        <view v-if="dataList.length == 0" class="noData">暂无结果</view>
      </view>

      <view v-else class="twelve_font record padding">
        <view class="search_history">
          <view class="fonts_26">搜索历史</view>
          <view class="flex wrap" v-if="from == 'order'">
            <text
              v-for="(item, index) in orderhistoryList"
              :key="index"
              @click="searchGood(item)"
              class="fonts_26"
              >{{ item }}</text
            >
          </view>
          <view class="flex wrap" v-else-if="from == 'returnorder'">
            <text
              v-for="(item, index) in returnorderhistoryList"
              :key="index"
              @click="searchGood(item)"
              class="fonts_26"
              >{{ item }}</text
            >
          </view>
          <view class="flex wrap" v-else>
            <text
              v-for="(item, index) in historyList"
              :key="index"
              @click="searchGood(item)"
              class="fonts_26"
              >{{ item }}</text
            >
          </view>
        </view>
      </view>

      <!-- 语音录入弹窗 -->
      <u-popup
        ref="speech"
        mode="bottom"
        v-model="showSpeech"
        :mask-close-able="false"
      >
        <view class="speech_box">
          <view class="head flex-btw">
            <text class="cancel" @click="closeSpeech(false)">取消</text>
            <image src="../../static/image/voice_on.png" mode=""></image>
            <text @click="closeSpeech(true)">确定</text>
          </view>
          <view class="wave flex-center">
            <!-- <button @longtap="longtapAction" @touchend="tapendAction" type="default">123</button>				 -->
            <view
              :class="[{ on: startSpeech }, 'voice_btn flex-center']"
              @longpress="longtapAction"
              @touchend="tapendAction"
            >
              <image
                v-if="startSpeech"
                class="img"
                src="../../static/image/voice_off.png"
                mode=""
              >
              </image>
              <view v-else class="push-txt">按住说话</view>
              <!-- <image  class="img" src="../../static/image/voice_on.png" mode=""></image> -->
              <!-- 加一层屏障，阻挡上面的图片，防止微信长按会弹出保存图片 -->
              <view class="film"></view>
            </view>
          </view>
        </view>
      </u-popup>

      <my-addcart ref="cart" :canshowprice="showPrice"></my-addcart>
    </view>

    <!-- 搜索时匹配的商品名称 -->
    <div v-show="showModalLog" class="modalLog">
      <div v-show="showLoading">
        <div v-if="goods_list.length > 0">
          <div
            class="modalLog-box"
            v-for="(item, index) in goods_list"
            :key="index"
            @click="searchGood(item.name)"
          >
            <text class="custom-icon custom-icon-chazhao"></text>
            <span class="modalLog-box-span">{{ item.name }}</span>
          </div>
        </div>
        <div v-else>
          <img class="gifImage" src="https://copartner.oss-cn-beijing.aliyuncs.com/logo/2312/08/tLoBDoCGvhHMvH8HhNhNIFPVb8vwR628I9Q6fKs8.png" alt="" />
        </div>
      </div>
      <div v-show="!showLoading">
        <img class="gifImage" src="https://copartner.oss-cn-beijing.aliyuncs.com/logo/2312/08/6EntBccIZTGhespoN27Y8l74XJJOMMH5bdC0Eehh.png" alt="" />
      </div>
    </div>
  </view>
</template>

<script>
// #ifdef H5
var wx = require("jweixin-module");
// #endif
// #ifdef MP-WEIXIN
var plugin = requirePlugin("WechatSI");
let manager = plugin.getRecordRecognitionManager();
// #endif

import { debounce } from "@/utils/index.js";

import { $https } from "@/static/js/request.js";
export default {
  data() {
    return {
      from: "goods", //从哪里的搜索进来
      zid: "", //订单需要
      hiddenSearch: false,
      value: "",
      historyList: [],
      orderhistoryList: [],
      returnorderhistoryList: [],
      hotList: [],
      page: 1,
      count: null,
      dataList: [],
      showPrice: null,
      placeholder: "请输入要查询的商品",
      haveConfig: false, //是否配置了微信（只需一次）
      showSpeech: false, //是否显示语音录入弹窗
      startSpeech: false, //开始录入
      background: { background: "#ffffff" },
      showModalLog: false, // 当输入框输入了商品后，展示该内容
      // 模态框内展示的内容
      goods_list: [],
      showLoading: false, // 加载中的动画
    };
  },
  onReady() {
    getApp().setTitle();
  },
  onLoad(options) {
    this.showPrice = uni.getStorageSync("canshowprice");
    if (options.from == "order") {
      this.from = options.from;
      this.placeholder = "请输入查询的订单号";
    } else if (options.from == "returnorder") {
      this.from = options.from;
      this.zid = options.zid != "null" ? options.zid : "";
      this.placeholder = "请输入查询的退货单号";
    }
  },
  onShow() {
    if (this.from == "order") {
      var orderhistoryList = uni.getStorageSync("orderhistoryList");
      this.orderhistoryList = orderhistoryList ? orderhistoryList : [];
    } else if (this.from == "returnorder") {
      var returnorderhistoryList = uni.getStorageSync("returnorderhistoryList");
      this.returnorderhistoryList = returnorderhistoryList
        ? returnorderhistoryList
        : [];
    } else if (this.from == "goods") {
      var historySearch = uni.getStorageSync("historySearch");
      this.historyList = historySearch ? historySearch : [];
    }
  },
  methods: {
    getData(page, value = this.value) {
      if (this.from == "order") {
        let params = {
          order_sn: value,
          page,
          size: 20,
        };
        this.zid &&
          Object.assign(params, {
            zid: this.zid,
          });
        $https("GET", "getOrderList", params, (res) => {
          var list = res.data.data.list;
          for (let i in list) {
            var ms = Number(list[i].created_at + "000");
            var now = new Date();
            now.setTime(ms);
            var date =
              now.getFullYear() +
              "-" +
              (now.getMonth() + 1) +
              "-" +
              now.getDate() +
              " " +
              now.getHours() +
              ":" +
              now.getMinutes() +
              ":" +
              now.getSeconds();
            list[i].createdTime = date;
          }
          this.dataList = this.dataList.concat(list);
          this.count = res.data.data.count;
          this.page = page;
        });
      } else if (this.from == "returnorder") {
        let params = {
          order_sn: value,
          page,
          size: 20,
        };
        this.zid &&
          Object.assign(params, {
            zid: this.zid,
          });
        $https("GET", "orderReturnList", params, (res) => {
          var list = res.data.data.list;
          for (let i in list) {
            var ms = Number(list[i].created_at + "000");
            var now = new Date();
            now.setTime(ms);
            var date =
              now.getFullYear() +
              "-" +
              (now.getMonth() + 1) +
              "-" +
              now.getDate() +
              " " +
              now.getHours() +
              ":" +
              now.getMinutes() +
              ":" +
              now.getSeconds();
            list[i].createdTime = date;
          }
          this.dataList = this.dataList.concat(list);
          this.count = res.data.data.count;
          this.page = page;
        });
      } else {
        $https(
          "GET",
          "goodsSearch",
          {
            name: value,
            page,
            size: 20,
          },
          (res) => {
            // this.showPrice = Boolean(res.data.data.look_goods_detail);
            var data = this.changePrice(res.data.data.goods_list);
            this.dataList = this.dataList.concat(data);
            this.count = res.data.data.count;
            this.page = page;
          },
          true
        );
      }
    },
    //处理价格规格sku
    changePrice(data) {
      var array = JSON.parse(JSON.stringify(data));
      for (let i in array) {
        //算出价格范围
        if (array[i].spu.length > 1) {
          var min, max;
          min = array[i].spu[0].market_price;
          if (array[i].spu[1].market_price < min) {
            max = Number(array[i].spu[0].market_price);
            min = Number(array[i].spu[1].market_price);
          } else {
            max = Number(array[i].spu[1].market_price);
            min = Number(array[i].spu[0].market_price);
          }
          for (let y in array[i].spu) {
            if (Number(array[i].spu[y].market_price) < min) {
              min = Number(array[i].spu[y].market_price);
            } else if (Number(array[i].spu[y].market_price) > max) {
              max = Number(array[i].spu[y].market_price);
            }
          }
          array[i].showPrice = `￥${min.toFixed(2)}~${max.toFixed(2)}`;
        } else if (array[i].spu.length == 1) {
          if (array[i].spu[0].activity_price) {
            //活动价
            array[i].showPrice = "￥" + array[i].spu[0].activity_price;
          } else if (array[i].spu[0].current_price == 1) {
            //是时价
            array[i].showPrice = "时价";
          } else {
            array[i].showPrice = "¥" + array[i].spu[0].market_price;
          }
          //只有一个规格时显示起订量、库存
          array[i].minimum = array[i].spu[0].minimum;
          array[i].designated_inventory = array[i].spu[0].designated_inventory;
          array[i].inventory_left = array[i].spu[0].inventory_left;
        }
        array[i].willBuyNum = 0;
      }
      return array;
    },

    searchGood(val) {
      this.showModalLog = false;
      if (val) {
        this.value = val;
      }
      var value = val || this.value;
      if (value) {
        var history =
          this.from == "order"
            ? this.orderhistoryList
            : this.from == "returnorder"
            ? this.returnorderhistoryList
            : this.historyList;
        var historyName =
          this.from == "order"
            ? "orderhistoryList"
            : this.from == "returnorder"
            ? "returnorderhistoryList"
            : "historySearch";

        var index = history.indexOf(value);
        if (index >= 0) {
          history.splice(index, 1);
        } else if (history.length >= 10) {
          history.pop();
        }
        history.unshift(value);
        uni.setStorageSync(historyName, history);

        this.hiddenSearch = true;
        this.dataList = [];
        this.getData(1, value);
      }
    },

    // 使用防抖等待500毫秒后获取数据
    inputAction: debounce(function (data) {
      var val = data.detail.value;
      // 当输入框有值时，将模态框展开；反之关闭
      if (val && this.placeholder == "请输入要查询的商品") {
        // 商品模态框打开
        this.showModalLog = true;
        // 加载功能打开
        this.showLoading = false;
        $https(
          "GETN",
          "goodsSearch",
          {
            name: val,
            page: 1,
            size: 20,
          },
          (res) => {
            if (res.data.errcode == 0) {
              this.goods_list = res.data.data.goods_list;
              this.showLoading = true;
            } else {
              uni.showToast({
                title: res.data.errmsg,
                duration: 2000,
              });
            }
            this.hiddenSearch = false;
          }
        );
      } else {
        this.showModalLog = false;
        this.hiddenSearch = false;
      }
      this.value = val;
    }, 500),

    //订单详情
    toDetail(id) {
      uni.navigateTo({
        url: `/subindex/order/detail?id=${id}`,
      });
    },
    //按钮事件
    btnAction(option) {
      console.log(option, "search");
      var type = option.type,
        id = option.id,
        msg = option.msg;

      if (type == "getOrderDetail") {
        uni.navigateTo({
          url: `/subpack/user/return_goods/return_list?id=${id}`,
        });
      }
      if (type == "toPay") {
        uni.navigateTo({
          url: `/subindex/shopcart/pay_for?id=${id}`,
        });
      } else if (type == "getLogistics") {
        // #ifdef H5
        uni.navigateTo({
          url: `/subindex/order/checkLog-h5?id=${id}`,
        });
        // #endif
        // #ifndef H5
        uni.navigateTo({
          url: `/subindex/order/checkLog-wx?id=${id}`,
        });
        // #endif
      } else {
        uni.showModal({
          content: `是否${msg}`,
          confirmColor: "#40AE36",
          success: (res) => {
            if (res.confirm) {
              $https(
                "GET",
                type,
                {
                  oid: id,
                },
                (res) => {
                  console.log(res, "rrrr");
                  if (res.data.errcode == 0) {
                    if (type == "onceAgain") {
                      //如果是再来一单，直接跳转到购物车
                      uni.switchTab({
                        url: "/pages/tabar/shopcart",
                      });
                    } else {
                      this.getData(1);
                    }
                  } else {
                    uni.showToast({
                      title: res.data.errmsg,
                      icon: "none",
                    });
                  }
                }
              );
            } else if (res.cancel) {
            }
          },
        });
      }
    },
    showPop() {
      // #ifdef MP-WEIXIN
      this.showSpeech = true;
      // #endif
      // #ifndef MP-WEIXIN
      if (this.haveConfig) {
        this.showSpeech = true;
      } else {
        this.getWxConfig();
      }
      // #endif
    },
    closeSpeech(type) {
      if (type) {
        this.searchGood();
      } else {
        this.value = "";
      }
      this.showSpeech = false;
    },
    getWxConfig() {
      this.showSpeech = true;
      $https(
        "GETN",
        "wxConfig",
        {
          type: "default",
        },
        (res) => {
          if (res.data.errcode == 0) {
            this.haveConfig = true;
            wx.config({
              debug: false, // 开启调试模式
              appId: res.data.data.appId, // 必填，公众号的唯一标识
              timestamp: res.data.data.timestamp, // 必填，生成签名的时间戳
              nonceStr: res.data.data.nonceStr, // 必填，生成签名的随机串
              signature: res.data.data.signature, // 必填，签名，见附录1
              jsApiList: [
                "startRecord",
                "stopRecord",
                "uploadVoice",
                "translateVoice",
              ], // 必填，需要使用的JS接口列表
            });
            this.showSpeech = true;
          } else {
            uni.showToast({
              icon: "none",
              title: "获取微信配置失败,请重试",
            });
          }
        },
        true
      );
    },
    //开始录音
    longtapAction() {
      this.startSpeech = true;
      // #ifndef MP-WEIXIN
      wx.startRecord();
      // #endif
      // #ifdef MP-WEIXIN
      manager.start();
      // #endif
    },
    //停止录音
    tapendAction() {
      this.startSpeech = false;
      // #ifndef MP-WEIXIN
      wx.stopRecord({
        success: (res) => {
          wx.translateVoice({
            localId: res.localId, // 需要识别的音频的本地Id，由录音相关接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: (result) => {
              // alert(result.translateResult); // 语音识别的结果
              // this.voiceResult = result.translateResult;
              this.value = result.translateResult.replace(/。/g, "");
            },
          });
        },
      });
      // #endif
      // #ifdef MP-WEIXIN
      manager.stop();
      var _this = this;
      manager.onStop = function (res) {
        _this.value = res.result.replace(/。/g, "");
      };
      // #endif
    },
    back() {
      // #ifdef H5
      window.history.back(-1);
      // #endif
      // #ifndef H5
      uni.navigateBack();
      // #endif
    },
  },
  onReachBottom() {
    var page = this.page;
    //如果请求到底就请求下一列表
    if (this.dataList.length < this.count) {
      page++;
      this.getData(page);
    } else {
      this.bottomText = "没有更多啦~";
    }
  },
};
</script>

<style scoped lang="scss">
/deep/.u-drawer {
  overflow: unset !important;
}
/deep/.u-title {
  font-weight: 900 !important;
  color: black !important;
  font-size: 36rpx !important;
}

.search_good {
  .noData {
    width: 100%;
    text-align: center;
    line-height: 80rpx;
  }

  .voice {
    width: 30rpx;
    height: 38rpx;
    margin-right: 20rpx;
  }

  .search_key {
    position: fixed;
    // #ifndef MP-WEIXIN
    top: calc(var(--status-bar-height) + 88rpx);
    // #endif
    // #ifdef MP-WEIXIN
    top: 0;
    // #endif
    left: 0;
    right: 0;
    background: #ffffff;
    z-index: 9;
    height: 100rpx;
    justify-content: space-between;
    border-bottom: 1rpx solid #e1e1e1;

    .cancel {
      margin-left: 26rpx;
      color: black;
      font-size: 26rpx;
    }

    .search {
      background-color: #f0f1f3;
      border-radius: 32rpx;
      flex-grow: 1;

      .search_input {
        width: 100%;
        padding-right: 20rpx;
        font-size: 28rpx;
      }
    }

    .custom-icon-chazhao {
      padding: 0 18rpx 0 38rpx;
    }

    .custom-icon-jiantou2 {
      font-weight: bold;
      color: black;
      margin-right: 40rpx;
      font-size: 40rpx;
    }

    .custom-icon-gouwu {
      color: #a3a3a3;
      font-size: 40rpx;
      margin-left: 36rpx;
    }

    input {
      height: 60rpx;
    }
  }

  .recommend_good {
    // #ifndef MP-WEIXIN
    margin-top: calc(var(--status-bar-height) + 100rpx);
    // #endif
    // #ifdef MP-WEIXIN
    margin-top: 100rpx;
    // #endif
    margin-bottom: 40rpx;

    .order {
      width: 100%;
      padding: 0 20rpx;
      border-radius: 10rpx;
      background: #fff;

      & + .order {
        margin-top: 20rpx;
      }
    }

    // .sign_good {
    // 	box-shadow: 0 2px 2px rgba(215, 239, 231, .38);
    // }
  }

  .record {
    // padding-top: calc(var(--status-bar-height) + 150rpx);
    padding-top: calc(var(--status-bar-height) + 110rpx);
  }

  .record text {
    background: #eaeaea;
    border-radius: 24rpx;
    padding: 6rpx 28rpx;
    margin: 12rpx 20rpx 0 0;
  }

  .hot_search {
    margin-top: 96rpx;
  }

  .speech_box {
    background: #fff;
    height: 600rpx;
    display: flex;
    flex-direction: column;

    .head {
      color: #4fa388;
      font-size: 28rpx;
      padding: 32rpx 44rpx;

      image {
        width: 34rpx;
        height: 46rpx;
      }

      .cancel {
        color: #cacaca;
      }
    }

    .wave {
      flex: 1;

      .voice_btn {
        position: relative;
        width: 200rpx;
        height: 200rpx;
        border-radius: 50%;
        border: 1px solid $dgreen;
        background: #fff;
        box-shadow: 0rpx 0rpx 30rpx $dgreen;

        &.on {
          background: $dgreen;
          box-shadow: 0rpx 0rpx 30rpx #999;
        }

        .img {
          width: 60rpx;
          height: 80rpx;
        }

        .push-txt {
          color: $dgreen;
          font-size: 16px;
          text-align: center;
          letter-spacing: 1px;
          width: 100rpx;
        }

        .film {
          position: absolute;
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}

.all_goods {
  display: grid;
  grid-template-columns: repeat(2, 360rpx);
  padding: 0 10rpx;
  gap: 10rpx;
}

.modalLog {
  width: 100%;
  height: calc(100vh - 101rpx);
  background: rgb(255, 255, 255);
  position: absolute;
  top: 101rpx;
  z-index: 9;
  &-box {
    border-bottom: 1rpx solid #f6f6f6;
    height: 66rpx;
    line-height: 66rpx;
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    padding-left: 30rpx;
    &-span {
      margin-left: 10rpx;
    }
  }
  .gifImage {
    width: 100%;
    height: 1220rpx;
  }
}
</style>
